package Service;

import Exceptions.BootstrapException;

import java.lang.reflect.Constructor;
import java.util.Properties;

public class BeanFactory {
    private static Class getClass(String className) throws BootstrapException
    {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new BootstrapException(BootstrapException.ErrorType.CLASS_NOTFOUND, "属性中标注的类不存在");
        }
    }
    public static Object creatObject(BeanDefinition bf) throws BootstrapException {
        Object obj;
        Class<?> clazz = getClass(bf.className);
        try {
            Constructor<?> con = clazz.getConstructor();
            obj = con.newInstance();
        }
        catch (Exception e){
            throw new BootstrapException(BootstrapException.ErrorType.CREATE_OBJECT_ERROR,"创建对象失败：请检查是否有无参构造函数");
        }
        var fields = clazz.getDeclaredFields();

        var mp = bf.getItems();
        for(var field: fields){
            field.setAccessible(true);
            if(mp.containsKey(field.getName())){
                try {
                    String value = mp.get(field.getName());
                    field.set(obj,value);
                }catch (Exception e){
                    throw new BootstrapException(BootstrapException.ErrorType.CREATE_OBJECT_ERROR,"创建对象失败，检查成员变量是否正确");
                }
            }
        }
        return obj;
    }


}
